package top.codingfly.examples;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.logging.LogLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.codingfly.netty.client.NettyClient;
import top.codingfly.netty.common.NettyPacket;

public class ClientExample {

    private final static Logger logger = LoggerFactory.getLogger(ClientExample.class);

    public static void main(String[] args) throws InterruptedException {
        NettyPacket heartbeatPacket = new ProtocolPacket(ProtocolPacket.heartbeatType);
        boolean reConnect = true;
        CommonHandler clientHandler = new CommonHandler() {
            // 解码之后, 会自动调handle方法
            @Override
            public <T> void handle(ChannelHandlerContext ctx, T msg) throws Exception {
                ProtocolPacket packet = (ProtocolPacket) msg;
                if (new Integer(2).equals(packet.type)) {
                    System.out.println(new String(packet.dataBytes));
                }
            }
        };

        NettyClient nettyClient = new NettyClient(clientHandler, heartbeatPacket, LogLevel.DEBUG, reConnect);
        nettyClient.connect("localhost", 1333);
        for (int i = 0; i < 999999; i++) {
            StringBuffer sb = new StringBuffer();
            if (i % 2 == 0) {
                sb.append("这里的问题就在于可读字节移动位置时会发生内存复制");
            } else {
                for (int j = 0; j < 33; j++) {
                    sb.append("这里的问题就在于可读字节移动位置时会发生内存复制");
                }
            }
            sb.append(i+"");
            ProtocolPacket packet = new ProtocolPacket(2, sb.toString().getBytes());
            try {
                nettyClient.send(packet);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            Thread.sleep(333);
//            nettyClient.close();
        }
        System.out.println();
    }

}
